<template>
	<view class="search">
		<view class="search-header">
			<view class="search-box u-flex">
				<u-icon name="arrow-left" color="#8d8d8d" size="44" @click="goBack"></u-icon>
				<view class="u-flex search-input">
					<u-icon name="search" color="#9F9F9F" size="36"></u-icon>
					<u-input :placeholder="$t('chat.chat_search_keyword')" v-model="keyword" @input="search"
						confirmType="search" @confirm="search" style="padding-left:30rpx"></u-input>
				</view>
				<view class="cancel-btn" @click="cancelSearch">{{$t('chat.chat_cancel')}}</view>
			</view>
		</view>
			<scroll-view scroll-y class="result-type" v-if="JSON.parse(JSON.stringify(list)).length > 0">
				<view class="t-conversation-item-container" v-for="(item,index) in list"
					:key="index">
					<view class="t-conversation-item">
						<view class="avatar-box">
							<image class="t-conversation-item-avatar"
								:src="handleUserAvatar(item.avatar, item)">
							</image>
						</view>
						<view class="t-conversation-item-content">
							<view class="u-flex u-row-between u-p-l-20 u-p-r-20 u-p-b-30">
								<view class="tui-result-name">{{item.nick}}</view>
								<text
									class="tui-result-time">{{getHistoryChatTime(item.time * 1000,$i18n,lang)}}</text>
							</view>
							<!-- 图片数据 -->
							<MessageText :id="item.flow + '-' + item.ID" :translate="dicttext1" :msgid="id1"
								v-if="item.type === types.MSG_TEXT" style="margin-top:-30rpx"
								:data="handleTextMessageShowContext(item)" :messageData="item"></MessageText>
							</view>
						</view>
					</view>
					<view class="empty-wrap" v-if="JSON.parse(JSON.stringify(list)).length === 0">
						<u-empty :text="$t('chat.chat_search_no_data')" mode="list"></u-empty>
					</view>
					<view style="height:50rpx"></view>
		  </scroll-view>
		<view v-if="showTabItem">
			<view class="search-tip">快速查找聊天内容</view>
			<view class="search-tabs">
				<view class="search-item" @click="$goPage('/TUIKit/TUIPages/TUISearch/detail',{conversationID: conversationID,groupID:groupID,type: 'image'})">
					<view class="icon-content">
						<i class="icon icon-tupian1" style="font-size: 36rpx;font-weight:700"></i>
					</view>
					<span class="search-tab-text">图片与视频</span>
				</view>
				<view class="search-item" @click="$goPage('/TUIKit/TUIPages/TUISearch/detail',{conversationID: conversationID,groupID:groupID,type:'file'})">
					<view class="icon-content">
					  <i class="icon icon-wenjianjia1" style="font-size: 36rpx;font-weight:700"></i>
					</view>
					<span class="search-tab-text">文件</span>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import timStorage from "../../utils/tim-storage.js";
	import MessageText from "../TUIChat/components/message-elements/message-text.vue";
	import {
		handleAvatar,
		handleTextMessageShowContext,
	} from "../../utils/untis";
	import {
		getHistoryChatTime
	} from "@/utils/date.js";
	import {
		useI18n
	} from "vue-i18n";
	import httpInterceptor from '@/utils/http.interceptor2.js';
	export default {
		components: {
			MessageText,
		},
		data() {
			return {
				conversationID: '',
				groupID: 0,
				keyword: '',
				list: [],
				messageList: [],
				groupMemberDict: [],
				current: 0,
				swiperCurrent: 0,
				types: uni.$TIM.TYPES,
				showTabItem: true,   //是否展示图片和文件
				empty_text: '没有找到相关记录',
				tabs: [{
						name: '全部'
					},
					{
						name: '图片与视频'
					},
					{
						name: '文件'
					},
				],
			}
		},
		computed: {
			lang() {
				return uni.getStorageSync('lang')
			}
		},
		onLoad(option) {
			this.conversationID = option.conversation_id || '';
			this.groupID = option.group_id || 0;
			this.getGroupMemberInfo();
			this.getMessageList()
		},
		methods: {
			handleAvatar,
			handleTextMessageShowContext,
			getHistoryChatTime,
			search(value) {
				console.log('vaalue-------------------------------------------------', value)
				this.showTabItem = false
				this.keyword = value
				uni.showLoading({
					title: this.$t('home.loading')
				})
				if(this.keyword === '') {
					this.list = []
					uni.hideLoading()
					this.showTabItem = true
				}else {
					if(this.messageList.length > 0) {
						let reg=/<[^<>]+>/g;
						this.list = this.messageList.filter(item => item.type === 'TIMTextElem' && item.payload.text.replace(reg,'').indexOf(this.keyword) !== -1);
						uni.hideLoading()
					}else {
						this.getMessageList()
					}
				}		
			},
			goBack() {
				uni.navigateBack()
			},
			getGroupMemberInfo() {
				let that = this;

				//从这获取本地头像姓名
				that.$http.get('/bbs/getUse/GroupImgAndId', {
					groupId: that.groupID
				}).then((res) => {
					that.groupMemberDict = res;
				}).catch(err => {})
			},
			handleUserAvatar(avatar, row) {
				console.log("row.from", row)
				console.log("this.groupMemberDict", this.groupMemberDict)
				if (this.groupMemberDict[row.from]) {
					console.log("this.groupMemberDict[row.from][1]", this.groupMemberDict[row.from][1])
					avatar = this.groupMemberDict[row.from][1];
				}
				return avatar;
			},
			async getMessageList() {

				let messageList = [];

				//获取本地缓存数据
				let storageMessage = [];
				storageMessage = await this.getStorageMsg();
				if (storageMessage.length) {
					messageList = [
						...storageMessage,
						...messageList
					];

				}

				//获取腾讯云 IM 数据
				let timMessageList = [];
				timMessageList = await this.getTimMsg(messageList);
				if (timMessageList.length) {
					messageList = [
						...timMessageList,
						...messageList
					];
				}

				//获取 iDOCK消息 数据
				let iDOCKMessage = [];
				console.log("多了嘛", messageList)
				iDOCKMessage = await this.getIDOCKMsg(messageList);
				console.log("iDOCKMessage", iDOCKMessage)
				if (iDOCKMessage.length) {
					messageList = [
						...iDOCKMessage,
						...messageList
					];
				}
				this.messageList = messageList;
				this.messageList.sort((a, b) => {
					return b.time - a.time;
				})
				this.messageList.forEach(item => {
					item.flow = 'in'
				})		
				if(this.keyword !== '') {
					let reg=/<[^<>]+>/g;
					this.list= this.messageList.filter(item => item.type === 'TIMTextElem' && item.payload.text.replace(reg,'').indexOf(this.keyword) !== -1);
					if(this.list.length === 0) {
						this.showTabItem = true
					}			 	
				}
		   uni.hideLoading();
			},
			async getStorageMsg() {

				let key_before = "uni-im-msg:" + this.conversationID
				let {
					keys,
					currentSize,
					limitSize
				} = uni.getStorageInfoSync()
				console.log("keys", keys);

				keys = keys.filter(k => k.indexOf(key_before) === 0)
				if (keys.length == 0) {
					return []
				}

				keys = keys.filter(k => k.indexOf(key_before) === 0)
				if (keys.length == 0) {
					return []
				}
				console.log("keys", keys);

				let list = [];
				keys.forEach(key => {

					let data = [];
					data = uni.getStorageSync(key) || [];
					list = [
						...data,
						...list,
					]
				})

				return list;
			},
			async getTimMsg(messageList) {

				let sequence = messageList[0].sequence || 0;
				let time = messageList[0].time || 0;
				let options = {
					conversationID: this.conversationID,
					count: 15,
				};

				let data = [];
				data = await this.getTimServerMessage(options, [], messageList);
				console.log(" 腾讯云数据哦", data);

				return data;
			},
			async getTimServerMessage(options, data = [], messageList) {


				let timMessageList = [];
				console.log("messageList", messageList)
				console.log("options", options)
				let imResponse = await uni.$TUIKit.getMessageList(options);
				console.log("imResponse", imResponse)
				timMessageList = imResponse.data.messageList || [];
				console.log("加完了", timMessageList)
				if (timMessageList.length) {

					//检查腾讯云消息是否最新的
					let oldMessageTime = messageList[0].time;
					timMessageList = timMessageList.filter(item => item.time < oldMessageTime)
					console.log("oldMessageTime", oldMessageTime)
					console.log("timMessageList", timMessageList)
					if (timMessageList.length) {
						data = [
							...timMessageList,
							...data,
						]
					}
				}
				console.log("加完了22", data)

				//检查是否拉完
				console.log("继续了。。。1111", imResponse.data.isCompleted)
				if (imResponse.data.isCompleted) {
					console.log(" 弹奏了", data)
					return data;
				}
				console.log("继续了。。。2222")

				//补充下条消息 ID
				if (imResponse.data.nextReqMessageID) {
					options.nextReqMessageID = imResponse.data.nextReqMessageID;
				}
				console.log("继续了。。。3333", options)
				return this.getTimServerMessage(options, data, messageList);
			},
			async getIDOCKMsg(messageList) {

				let data = [];
				data = await this.getIDOCKServerMessage(data, messageList);
				console.log(" iDOCK 数据哦", data);

				return data;
			},
			async getIDOCKServerMessage(data = [], messageList) {

				//获取最新消息时间
				let lastMessageTime = 0;
				if (data.length > 0) {
					lastMessageTime = data[0].time;
				} else if (messageList.length > 0) {
					lastMessageTime = messageList[0].time;
				}

				console.log("lastMessageTime", lastMessageTime)
				let iDOCKMessage = [];
				await httpInterceptor.get('/mgr/tim/chat/conversation/history/message', {
					conversation_id: this.conversationID,
					last_message_time: lastMessageTime
				}).then(res => {
					iDOCKMessage = res;
					console.log("res", res);
					if (res.length) {
						data = [
							...res,
							...data,
						]
					}
				})

				if (iDOCKMessage.length == 0) {
					console.log("直接退出拉")
					return data;
				}

				return this.getIDOCKServerMessage(data, messageList);
			},
			cancelSearch() {
				this.showTabItem = true
				this.list = []
				this.keyword = ''
			},
		},
	}
</script>

<style lang="scss" scoped>
	.search {
		white-space: normal;
		word-break: break-all;
		margin-top: 60rpx;
		height: 100vh;
	}

	.search-result {
		height: 90vh;
		background-color: #fff;
		margin-top: 16rpx;
	}

	.search-header {
		padding: 30rpx;
		border-bottom: 1px solid #e6e5e8;
	}

	.search-box {
		justify-content: space-between;
	}

	.search-input {
		padding: 0 10rpx 0 20rpx;
		border-radius: 16rpx;
		background-color: #fff;
		flex: 1;
		margin-left: 10rpx;
	}

	.cancel-btn {
		padding: 0 10rpx 0 28rpx;
		font-size: 32rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
			color: #2979ff;
	}
	.search-tip {
		text-align: center;
		color: #999;
		margin-bottom: 20rpx;
		margin-top: 100rpx;
		letter-spacing: 5rpx;
	}
	.no-border {
			border: none
		}
	
		.t-conversation-item-container {
			width: 100%;
			padding: 10rpx;
			background-color: #fff;
	
			.t-conversation-item {
				width: 100%;
				display: flex;
	
				.t-conversation-item-content {
					flex: 1;
					border-bottom: 2rpx solid #EEF0F3;
	
					.tui-result-name {
						font-size: 28rpx;
						font-family: Adobe Heiti Std;
						font-weight: normal;
						color: #868686;
					}
	
					.tui-result-time {
						font-size: 26rpx;
						color: #cdcdcd;
					}
				}
			}
		}
	
		.result-type {
			margin-top: 16rpx;
			height: 90vh;
		}
	
	
	
		.avatar-box {
			position: relative;
			display: inline-flex;
		}
	
		.t-conversation-item-avatar {
			position: relative;
			width: 72rpx;
			height: 72rpx;
			border-radius: 16rpx;
			/*padding-left: 40rpx;*/
			/*padding-right: 24rpx;*/
			/*padding-bottom: 28rpx;*/
			/*padding-top: 28rpx;*/
			margin: 0 14rpx 0 28rpx;
			overflow: auto;
		}
	
	
	
	
		.tui-result-message {
			font-size: 27rpx;
			font-family: Adobe Heiti Std;
			font-weight: normal;
			color: #98A0A1;
			line-height: 30rpx;
		}
  .search-tabs {
		display: flex;
		justify-content: center;
		.search-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			&:first-child {
				margin-right: 80rpx;
			}
			.icon-content {
				width: 100rpx;
				height: 100rpx;
				border-radius: 100rpx;
				background-color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 40rpx;
				color: #2979ff;
			}
			.search-tab-text {
				font-size: 26rpx;
				color: #999;
				margin-top:10rpx;
			}
		}
	}
	
</style>
